package com.example.myapplication;

import com.example.myapplication.shortvideo.utils.GsonUtil;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * @author: rongfeng
 * @date: 2020/9/2
 * @description
 */
public class youdaoImg {
    static volatile int index = 0;

    public static List<String> words;
    static ExecutorService pool;

    static volatile List<String> shibai = new ArrayList<>();


    public static void main(String[] args) {
        pool = Executors.newFixedThreadPool(10);
        words = new ArrayList<>(new ReadWords().start3());
        System.out.println(words.size());
        start();
    }

    public static void start() {
        for (int i = 0; i < 10; i++) {
            nextClass();
        }
    }


    public synchronized static void nextClass() {
        pool.execute(new Runnable() {
            @Override
            public synchronized void run() {
                if (index < words.size()) {
                    String word = words.get(index);
                    String url = getUrl(word);
                    index++;
                    if (isExists(word)) {
                        nextClass();
                    } else {
                        new Query2().getDns(url, word);
                    }
                }
            }
        });

        if (index == words.size()) {
            System.out.println("失败 " + shibai.size());
            for (String word :
                    shibai) {
                System.out.println(word);
            }

        }


    }

    public static String getUrl(String word) {
        return "http://www.youdao.com/w/" + word + "/#keyfrom=dict2.top";
    }


    public static class Query2 {
        public void getDns(String url, String word) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .build();
            final Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    System.out.println(word);
                    shibai.add(word);
                }

                @Override
                public void onResponse(Call call, @NotNull okhttp3.Response response) throws IOException {
                    if (response.body() != null) {
                        String html = response.body().string();
                        getImg(html, word);
                        nextClass();
                    }
                }
            });
        }


        public static void getImg(String html, String word) {
            String tag1 = "<div class=\"img-list\">";
            String tag2 = "\"";
            int index1 = html.indexOf(tag1);
            if (index1 > 0) {
                String html1 = html.substring(index1 + tag1.length());

                String tag3 = "<a><img src=\"";
                int index2 = html1.indexOf(tag3);
                String html2 = html1.substring(index2 + tag3.length());

                int last1 = html2.indexOf(tag2);
                String html3 = html2.substring(0, last1  );

                download(html3, word);

            }
        }
    }


    public static boolean isExists(String word) {
        File file = new File("D:\\wrf\\qn2\\" + word + ".png");
        System.out.println("ssss " + index + " " + file.exists());
        return file.exists();
    }


    public static void download(String sourceUrl, String word) {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;
        URL url = null;
        try {
            url = new URL(sourceUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        InputStream inStream = null;
        FileOutputStream fs = null;
        try {
            URLConnection conn = url.openConnection();
            inStream = conn.getInputStream();

            fs = new FileOutputStream("D:\\wrf\\qn2\\" + word + ".png");

            byte[] buffer = new byte[1024];
            int length;
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }

        } catch (FileNotFoundException e) {
            System.out.println(word);
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fs != null) {
                try {
                    fs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
